package com.alks.function.service.impl.chengKong;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.enums.chengkong.DefineEnum;
import com.alks.entity.data.enums.chengkong.NoteEnum;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.function.data.dto.chengKong.assort.*;
import com.alks.function.data.request.chengKong.*;
import com.alks.function.mapper.chengKong.*;
import com.alks.function.service.chengKong.RAndDUsageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
@Slf4j
public class RAndDUsageServiceImpl implements RAndDUsageService {

    @Resource
    private RAndDUsageMapper rAndDUsageMapper;

    @Resource
    private LargeCargoTypeMapper largeCargoTypeMapper;

    /**
     * 新增
     * @param map
     * @return
     */
    @Override
    public ResponseInfo getStyleUsageAdd(Map<String, String> map) {
        //获取键值
        String styleNo = map.get("styleNo");
        String styleColor = map.get("styleColor");
        String colorCode = map.get("colorCode");

        if (StringUtils.isEmpty(styleNo)) {
            return ResponseInfo.error("请输入型体!");
        }

        if (StringUtils.isEmpty(styleColor)) {
            return ResponseInfo.error("请输入颜色名称!");
        }

        //拿到型体状态
        YfStyle yfStyle = rAndDUsageMapper.getStyle(styleNo);
        if (yfStyle == null) {
            log.error("型体:{},基本资料未建档,不能新增!", styleNo);
            return ResponseInfo.error("型体:" + styleNo + "基本资料未建档,不能新增!");
        }

        //查询型体配色资料
        YfStyleColorDetail styleColorDetail = rAndDUsageMapper.getStyleColorDetail(styleNo, styleColor);
        if (styleColorDetail == null) {
            return ResponseInfo.error("型体:" + styleNo + ",颜色:" + styleColor +",未建档,不能新增!");
        }

        //研发型体用量建档暂时不需要颜色代码的判断
/*        if (colorCode == null || colorCode.isEmpty()) {
            if (colorCode != styleColorDetail.getColorCode()) {
                log.error("型体:{},颜色:{},颜色代号:{},未建档,不能新增!", styleNo, styleColor, colorCode);
                return ResponseInfo.error("型体:" + styleNo + ",颜色:" + styleColor + ",颜色代号:"+colorCode + ",未建档,不能新增!");
            }
        } else {
            if (!colorCode.equals(styleColorDetail.getColorCode())) {
                log.error("型体:{},颜色:{},颜色代号:{},未建档,不能新增!", styleNo, styleColor, colorCode);
                return ResponseInfo.error("型体:" + styleNo + ",颜色:" + styleColor + ",颜色代号:"+colorCode + ",未建档,不能新增!");
            }
        }*/

        if (yfStyle.getCfmFlag() == null || yfStyle.getCfmFlag().isEmpty()) {
            return ResponseInfo.error("型体:" + styleNo + "未检验,不能添加!");
        }

        //查询是否存在
        String styleUsage = rAndDUsageMapper.getStyleUsage(styleNo, styleColor);
        if (!ObjectUtils.isEmpty(styleUsage)) {
            return ResponseInfo.error("型体:" + styleNo + ",颜色:" + styleColor+ ",已存在!");
        }

        //封装数据
        YfBomHeadNew2 yfBomHeadNew2 = new YfBomHeadNew2();
        yfBomHeadNew2.setCompanyId(UserIdThread.get().getCompanyId());
        yfBomHeadNew2.setStyleNo(styleNo);
        yfBomHeadNew2.setStyleColor(styleColor);
        yfBomHeadNew2.setSysUser(UserIdThread.get().getUserName());
        yfBomHeadNew2.setSysDate(LocalDateTime.now());
        yfBomHeadNew2.setBaseSize(yfStyle.getBaseSize());
        yfBomHeadNew2.setColorCode(colorCode);

        //新增
        rAndDUsageMapper.addStyleUsage(yfBomHeadNew2);

        return ResponseInfo.ok("操作成功!");
    }

    @Resource
    private PartMapper partMapper;

    @Resource
    private GeneralMaterialsMapper generalMaterialsMapper;

    /**
     * 保存
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getStyleUsageDetailAdd(StyleColorMaterialAddRequest request) {

        //判断参数
        if (StringUtils.isEmpty(request.getStyleNo()) || StringUtils.isEmpty(request.getStyleColor())) {
            log.error("型体:{},颜色:{},不能为空!", request.getStyleNo(), request.getStyleColor());
            return ResponseInfo.error("型体或型体颜色不能为空!");
        }

        String companyId = UserIdThread.get().getCompanyId();
        if (!ObjectUtils.isEmpty(request.getStyleColorMaterialRequests())) {

            //判断部位是否存在
            for (StyleColorMaterialRequest s : request.getStyleColorMaterialRequests()) {
                if (StringUtils.isEmpty(s.getPartName())) {
                    log.error("请输入部位!");
                    return ResponseInfo.error("请输入部位!");
                }

                String partName = partMapper.getPartName(s.getPartName());
                if (StringUtils.isEmpty(partName)) {
                    log.error("部位:{},输入错误!", s.getPartName());
                    return ResponseInfo.error(s.getPartName()+"部位输入错误!");
                }
            }

            //判断是否已检验
            String flag = rAndDUsageMapper.checkout(request.getStyleNo(), request.getStyleColor());
            if (!ObjectUtils.isEmpty(flag) && flag.equals(DefineEnum.CHECKOUT_FLAG.getValue())) {
                log.error("型体:{},颜色:{},已检验,不可处理!", request.getStyleNo(), request.getStyleColor());
                return ResponseInfo.error("型体:" + request.getStyleNo() + ",颜色:" + request.getStyleColor() + ",已检验，不可处理!");
            }

            //处理数据
            List<YfBomPartNew2> list = request.getStyleColorMaterialRequests().stream().map(s -> {

                YfBomPartNew2 yfBomPartNew2 = new YfBomPartNew2();
                BeanUtil.copyProperties(s, yfBomPartNew2);
                yfBomPartNew2.setCompanyId(companyId);
                yfBomPartNew2.setStyleNo(request.getStyleNo());
                yfBomPartNew2.setMtlNo2(s.getMtlNo());
                yfBomPartNew2.setStyleColor(request.getStyleColor());

                //判断计算方式
                if (!StringUtils.isEmpty(s.getUsageType())) {
                    switch (s.getUsageType()) {
                        case "全码":
                            yfBomPartNew2.setUsageType("F");
                            break;
                        case "中间码":
                            yfBomPartNew2.setUsageType("M");
                            break;
                        case "基本码":
                            yfBomPartNew2.setUsageType("B");
                            break;
                        default:
                            yfBomPartNew2.setUsageType(null);
                    }
                }

                //判断是否捡料
                if (!StringUtils.isEmpty(s.getNoLotUsage())) {
                    switch (s.getNoLotUsage()) {
                        case "0":
                            yfBomPartNew2.setNoLotUsage("Y");
                            break;
                        default:
                            yfBomPartNew2.setNoLotUsage(null);
                    }
                }
                return yfBomPartNew2;
            }).collect(Collectors.toList());

            //重排序号
            //生成一个整数流
            List<YfBomPartNew2> updatedList = IntStream.range(0, list.size())
                    //映射对象
                    .mapToObj(i -> {
                        YfBomPartNew2 yfBomPartNew2 = new YfBomPartNew2();
                        BeanUtil.copyProperties(list.get(i), yfBomPartNew2);
                        yfBomPartNew2.setSeqNo(String.valueOf(i + 1));
                        return yfBomPartNew2;
                    })
                    .collect(Collectors.toList());
            //删除
            rAndDUsageMapper.delStyleUsageDetail(request.getStyleNo(), request.getStyleColor());
            //添加
            rAndDUsageMapper.addStyleUsageDetail(updatedList);

        } else {
            //删除
            rAndDUsageMapper.delStyleUsageDetail(request.getStyleNo(), request.getStyleColor());
        }

        //型体颜色备注
        generalMaterialsMapper.updateStyleColorRemark(request.getStyleNo(), request.getStyleColor(), request.getStyleColorRemark());

        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 检核0/1取消检核
     * @param map
     * @param choose
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getCheckOut(Map<String, String> map, Integer choose) {
        String styleNo = map.get("styleNo");
        String styleColor = map.get("styleColor");
        //判断是否已检验
        String flag = rAndDUsageMapper.checkout(styleNo, styleColor);
        if (choose == 0) {
            if (!ObjectUtils.isEmpty(flag) && flag.equals(DefineEnum.CHECKOUT_FLAG.getValue())) {
                return ResponseInfo.error("当前行颜色已检验,不能在检验!!!");
            }

            List<YfBomPartNew2> styleColorMaterialList = rAndDUsageMapper.getStyleColorMaterialList(styleNo, styleColor);
            if (!ObjectUtils.isEmpty(styleColorMaterialList)){
                // 记录为空字段的次数
                int count = 0;
                int usageCount=0;

                for (YfBomPartNew2 yfBomPartNew2 : styleColorMaterialList) {
                    if (ObjectUtils.isEmpty(yfBomPartNew2.getMtlNo2())){
                        count++;
                    }
                    if (ObjectUtils.isEmpty(yfBomPartNew2.getUsage())){
                        usageCount++;
                    }
                }
                 if (count>0){
                     return ResponseInfo.error("型体颜色BOM有"+count+"个物料编码为空的记录!");
                 }
                 if (usageCount>0){
                     return ResponseInfo.error("型体颜色BOM有"+usageCount+"个用量为空的记录!");
                 }
            }else {
                return ResponseInfo.error("型体:"+styleNo + ",颜色:"+styleColor + ",BOM资料为空!");
            }
            //获取用户名
            SysUserTokenDTO dto = UserIdThread.get();
            String userName = dto.getUserName();
            //检验状态
            String cfmFlag = "Y";
            rAndDUsageMapper.updateCheckOutFlag(userName, LocalDateTime.now(), cfmFlag, styleNo, styleColor);
            bomChangeBak(styleNo,styleColor,styleColorMaterialList,dto.getCompanyId(),userName);
        } else {
            if (ObjectUtils.isEmpty(flag)){
                return ResponseInfo.error("当前行颜色未检验，不能取消检验!!!");
            }
            rAndDUsageMapper.updateCheckOutFlag(null, null, null, styleNo, styleColor);
            rAndDUsageMapper.delYfBomPartNew2Bak(styleNo, styleColor);
            List<YfBomPartNew2> styleColorMaterialList = rAndDUsageMapper.getStyleColorMaterialList(styleNo, styleColor);
            if (!ObjectUtils.isEmpty(styleColorMaterialList)){
                rAndDUsageMapper.addStyleUsageDetailBak(styleColorMaterialList);
            }
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * bom修改写入日志
     * @param styleNo
     * @param styleColor
     * @param list
     */
    public void bomChangeBak(String styleNo, String styleColor, List<YfBomPartNew2> list, String companyId, String userName) {
        List<YfBomPartNew2> boms = rAndDUsageMapper.getStyleColorMaterialList2(styleNo, styleColor);
        if (!ObjectUtils.isEmpty(boms)) {
            List<YfBomChange> changes = new ArrayList<>();
            String[] changeTypes = {
                    "材料变更", "尺码起变更", "尺码止变更", "供应商变更",
                    "用量变更", "计算方式变更", "领用单位变更"
            };
            for (YfBomPartNew2 oldPart : boms) {
                boolean partExistsInList = list.stream().anyMatch(newPart ->
                        newPart.getPartName().equals(oldPart.getPartName()) &&
                                newPart.getSegment().equals(oldPart.getSegment()));
                if (!partExistsInList) {
                    YfBomChange yfBomChange = getYfBomChange(styleNo, styleColor, companyId, userName, oldPart.getPartName(), oldPart.getSegment());
                    yfBomChange.setChangeType("删除部件");
                    changes.add(yfBomChange);
                } else {
                    for (YfBomPartNew2 newPart : list) {
                        if (newPart.getPartName().equals(oldPart.getPartName()) &&
                                newPart.getSegment().equals(oldPart.getSegment())) {
                            for (int i = 0; i < changeTypes.length; i++) {
                                String oldValue = getChangeName(oldPart, i);
                                String newValue = getChangeName(newPart, i);
                                if (!newValue.equals(oldValue)) {
                                    String remark = getRemark(oldValue,newValue);
                                    YfBomChange yfBomChange = getYfBomChange(styleNo, styleColor, companyId, userName, oldPart.getPartName(), oldPart.getSegment());
                                    yfBomChange.setChangeType(changeTypes[i]);
                                    yfBomChange.setRemark(remark);
                                    changes.add(yfBomChange);
                                }
                            }
                            break;
                        }
                    }
                }
            }
            for (YfBomPartNew2 newPart : list) {
                boolean partExistsInBoms = boms.stream().anyMatch(oldPart ->
                        oldPart.getPartName().equals(newPart.getPartName()) &&
                                oldPart.getSegment().equals(newPart.getSegment()));
                if (!partExistsInBoms) {
                    YfBomChange yfBomChange = getYfBomChange(styleNo, styleColor, companyId, userName, newPart.getPartName(), newPart.getSegment());
                    yfBomChange.setChangeType("增加部件");
                    changes.add(yfBomChange);
                }
            }
            if (!ObjectUtils.isEmpty(changes)) {
                rAndDUsageMapper.addYfBomChangeList(changes);
            }
        }
    }


    /**
     * 获取备注
     * @param oldString
     * @param newString
     * @return
     */
    private String getRemark(String oldString, String newString){
        String remark = "原:" + oldString + "----" + "新:" + newString;
        return remark;
    }

    /**
     * 获取材料名称
     * @param s
     * @param type 0 材料变更
     *             1 尺码起变更
     *             2 尺码止变更
     *             3 供应商变更
     *             4 用量变更
     *             5 计算方式变更
     *             6 领用单位变更
     * @return
     */
    private String getChangeName(YfBomPartNew2 s,int type){
        StringBuilder name = new StringBuilder();
        switch (type){
            case 0:
                if (s.getMtlColor() != null && !s.getMtlColor().isEmpty()) {
                    name.append(s.getMtlColor());
                }else {
                    name.append("//");
                }
                if (s.getMtlName() != null && !s.getMtlName().isEmpty()) {
                    if (name.length() > 0) {
                        name.append("//");
                    }
                    name.append(s.getMtlName());
                }else {
                    name.append("//");
                }
                if (s.getMtlSpec() != null && !s.getMtlSpec().isEmpty()) {
                    if (name.length() > 0) {
                        name.append("//");
                    }
                    name.append(s.getMtlSpec());
                }else {
                    name.append("//");
                }
                if (s.getMtlUnit() != null && !s.getMtlUnit().isEmpty()) {
                    if (name.length() > 0) {
                        name.append("//");
                    }
                    name.append(s.getMtlUnit());
                }else {
                    name.append("//");
                }
                break;
            case 1:
                if (s.getSize1() != null && !s.getSize1().isEmpty()){
                    name.append(s.getSize1());
                }else {
                    name.append("");
                }
                break;
            case 2:
                if (s.getSize2() != null && !s.getSize2().isEmpty()){
                    name.append(s.getSize2());
                }else {
                    name.append("");
                }
                break;
            case 3:
                if (s.getVendor() != null && !s.getVendor().isEmpty()){
                    name.append(s.getVendor());
                }else {
                    name.append("");
                }
                break;
            case 4:
                if (s.getUsage() != null){
                    float v = s.getUsage().floatValue();
                    String value = String.valueOf(v);
                    name.append(value);
                }else {
                    name.append("");
                }
                break;
            case 5:
                if (s.getUsageType() != null && !s.getUsageType().isEmpty()){
                    name.append(s.getUsageType());
                }else {
                    name.append("");
                }
                break;
            case 6:
                if (s.getDrawDept() != null && !s.getDrawDept().isEmpty()){
                    name.append(s.getDrawDept());
                }else {
                    name.append("");
                }
                break;
        }
        return name.toString();
    }

    /**
     * bom修改日志记录
     * @param styleNo
     * @param styleColor
     * @param companyId
     * @param userName
     * @param partName
     * @param segment
     * @return
     */
    public YfBomChange  getYfBomChange(String styleNo, String styleColor,String companyId,String userName,String partName,String segment){
        YfBomChange yfBomChange = new YfBomChange();
        yfBomChange.setCompanyId(companyId);
        yfBomChange.setStyleNo(styleNo);
        yfBomChange.setStyleColor(styleColor);
        yfBomChange.setPartName(partName);
        yfBomChange.setSegment(Integer.valueOf(segment));
        yfBomChange.setSysUser(userName);
        yfBomChange.setSysDate(LocalDateTime.now());
        return yfBomChange;
    }

    /**
     * 注意事项建档
     * @param map
     * @return
     */
    @Override
    public ResponseInfo getPrecautionsForFilingAdd(Map<String, String> map) {
        //获取键值
        String styleNo = map.get("styleNo");
        String styleColor = map.get("styleColor");

        //查询注意事项列表
        List<YfBomMemoNew2Dto> list = rAndDUsageMapper.getPrecautionsForFiling(styleNo, styleColor);
        if (ObjectUtils.isEmpty(list)) {
            List<Map<String, String>> noteList = NoteEnum.noteList();
            String companyId = UserIdThread.get().getCompanyId();

            List<YfBomMemoNew2> yfBomMemoNew2List = noteList.stream().map(s -> {
                YfBomMemoNew2 yfBomMemoNew2 = new YfBomMemoNew2();
                yfBomMemoNew2.setCompanyId(companyId);
                yfBomMemoNew2.setStyleNo(styleNo);
                yfBomMemoNew2.setStyleColor(styleColor);
                yfBomMemoNew2.setSeqNo(BigDecimal.valueOf(Long.parseLong(s.get("seqNo"))));
                yfBomMemoNew2.setSeqName(s.get("seqName"));
                return yfBomMemoNew2;
            }).collect(Collectors.toList());
            //新增
            rAndDUsageMapper.addPrecautionsForFiling(yfBomMemoNew2List);
        }

        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 注意事项建档列表
     * @param map
     * @return
     */
    @Override
    public ResponseInfo getPrecautionsForFilingList(Map<String, String> map) {

        //获取键值
        String styleNo = map.get("styleNo");
        String styleColor = map.get("styleColor");

        //查询注意事项列表
        List<YfBomMemoNew2Dto> list = rAndDUsageMapper.getPrecautionsForFiling(styleNo, styleColor);
        return ResponseInfo.ok(list);
    }

    /**
     * 注意事项建档保存
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getPrecautionsForFilingSave(PrecautionsForFilingUpdateRequest request) {

        if (ObjectUtils.isEmpty(request.getStyleNo()) || ObjectUtils.isEmpty(request.getStyleColor())) {
            log.error("型体:{},颜色:{},必要参数为空!", request.getStyleNo(), request.getStyleColor());
            return ResponseInfo.error("必要参数为空!");
        }

        String companyId = UserIdThread.get().getCompanyId();
        if (!ObjectUtils.isEmpty(request)) {
            if (!ObjectUtils.isEmpty(request.getList())) {
                List<YfBomMemoNew2> yfBomMemoNew2List = request.getList().stream().map(s -> {
                    YfBomMemoNew2 yfBomMemoNew2 = new YfBomMemoNew2();
                    BeanUtil.copyProperties(s, yfBomMemoNew2);
                    yfBomMemoNew2.setCompanyId(companyId);
                    yfBomMemoNew2.setStyleNo(request.getStyleNo());
                    yfBomMemoNew2.setStyleColor(request.getStyleColor());

                    return yfBomMemoNew2;
                }).collect(Collectors.toList());

                //删除
                rAndDUsageMapper.delPrecautionsForFiling(request.getStyleNo(), request.getStyleColor());

                //添加
                rAndDUsageMapper.addPrecautionsForFiling(yfBomMemoNew2List);
            } else {
                //删除
                rAndDUsageMapper.delPrecautionsForFiling(request.getStyleNo(), request.getStyleColor());
            }
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 复制资料
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getCopyingMaterials(CopyingMaterialsRequest request) {
        if (StringUtils.isEmpty(request.getNewStyleNo())) {
            return ResponseInfo.error("请输入新型体资料!");
        }
        if (StringUtils.isEmpty(request.getNewStyleColor())) {
            return ResponseInfo.error("请输入新颜色资料!");
        }
        if (request.getStyleNo().equals(request.getNewStyleNo())&&request.getStyleColor().equals(request.getNewStyleColor())){
            return ResponseInfo.error("新旧型体/颜色相同!");
        }

        //查询型体是否建档
        String styleUsage = rAndDUsageMapper.getStyleUsage(request.getNewStyleNo(),request.getNewStyleColor());
        if (ObjectUtils.isEmpty(styleUsage)) {
            return ResponseInfo.error("新型体/颜色需要新增!");
        }

        //查询型体颜色材料表是否存在
        String styleColorMaterial = rAndDUsageMapper.getStyleColorMaterial(request.getNewStyleNo(),request.getNewStyleColor());
        if (!ObjectUtils.isEmpty(styleColorMaterial)) {
            log.error("新型体:{}/颜色:{},BOM资料已经存在!", request.getNewStyleNo(), request.getNewStyleColor());
            return ResponseInfo.error("新型体/颜色BOM资料已经存在!");
        }
        //要复制的信息
        List<YfBomPartNew2> styleColorMaterialList = rAndDUsageMapper.getStyleColorMaterialList(request.getStyleNo(),
                request.getStyleColor());

        if (!ObjectUtils.isEmpty(styleColorMaterialList)) {
            //0要颜色,1不要颜色
            switch (request.getWantColor()) {
                case "0":
                    List<YfBomPartNew2> list = styleColorMaterialList.stream().map(s -> {
                        YfBomPartNew2 yfBomPartNew2 = new YfBomPartNew2();
                        BeanUtil.copyProperties(s, yfBomPartNew2);
                        yfBomPartNew2.setStyleNo(request.getNewStyleNo());
                        yfBomPartNew2.setStyleColor(request.getNewStyleColor());
                        yfBomPartNew2.setStyleCopyTemp(request.getStyleNo());
                        yfBomPartNew2.setColorCopyTemp(request.getStyleColor());
                        return yfBomPartNew2;
                    }).collect(Collectors.toList());

                    //新增
                    rAndDUsageMapper.addStyleUsageDetail(list);
                    break;
                default:
                    List<YfBomPartNew2> list2 = styleColorMaterialList.stream().map(s -> {
                        YfBomPartNew2 yfBomPartNew2 = new YfBomPartNew2();
                        BeanUtil.copyProperties(s, yfBomPartNew2);
                        yfBomPartNew2.setMtlNo(null);
                        yfBomPartNew2.setMtlNo2(null);
                        yfBomPartNew2.setMtlColor(null);
                        yfBomPartNew2.setStyleNo(request.getNewStyleNo());
                        yfBomPartNew2.setStyleColor(request.getNewStyleColor());
                        yfBomPartNew2.setStyleCopyTemp(request.getStyleNo());
                        yfBomPartNew2.setColorCopyTemp(request.getStyleColor());
                        return yfBomPartNew2;
                    }).collect(Collectors.toList());

                    //新增
                    rAndDUsageMapper.addStyleUsageDetail(list2);
                    break;
            }
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 删除型体打勾记录
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getDeleteTickRecords(StyleR2DDelRequest request) {
        if (ObjectUtils.isEmpty(request.getSeqNoList())) {
            log.error("型体:{},颜色:{},选择记录为空!",
                    request.getStyleNo(),
                    request.getStyleColor(),
                    request.getSeqNoList());
            return ResponseInfo.error("请选择记录!");
        }

        rAndDUsageMapper.deleteTickRecords(request.getStyleNo(),
                request.getStyleColor(),
                request.getSeqNoList());

        //查询型体颜色BOM
        List<YfBomPartNew2> list = rAndDUsageMapper.getStyleColorMaterialList(request.getStyleNo(), request.getStyleColor());
        if (!ObjectUtils.isEmpty(list)) {

            //生成一个整数流
            List<YfBomPartNew2> updatedList = IntStream.range(0, list.size())
                    //映射对象
                    .mapToObj(i -> {
                        YfBomPartNew2 yfBomPartNew2 = new YfBomPartNew2();
                        BeanUtil.copyProperties(list.get(i), yfBomPartNew2);
                        yfBomPartNew2.setSeqNo(String.valueOf(i + 1));
                        return yfBomPartNew2;
                    })
                    .collect(Collectors.toList());
            //删除
            rAndDUsageMapper.delStyleUsageDetail(request.getStyleNo(), request.getStyleColor());

            //添加
            rAndDUsageMapper.addStyleUsageDetail(updatedList);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 整单型体颜色删除
     * @param map
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getDeleteStyleColorList(Map<String, String> map) {

        //获取键值
        String styleNo = map.get("styleNo");
        String styleColor = map.get("styleColor");

        if (ObjectUtils.isEmpty(styleNo) || ObjectUtils.isEmpty(styleColor)) {
            log.error("型体:{},颜色:{},参数为空!", styleNo, styleColor);
            return ResponseInfo.error("参数为空!");
        }

        //判断是否检验
        String flag = rAndDUsageMapper.checkout(styleNo, styleColor);
        if (!ObjectUtils.isEmpty(flag) && flag.equals(DefineEnum.CHECKOUT_FLAG.getValue())) {
            log.error("型体:{}/颜色:{}BOM资料已检验,不能删除!", styleNo, styleColor);
            return ResponseInfo.error("型体:" + styleNo + "/颜色:" + styleColor + ",BOM资料已检验,不能删除!");
        }

        //判断型体是否被关联大货BOM资料
        Integer headNew2 = rAndDUsageMapper.getSdBomHeadNew2(styleNo, styleColor);
        if (headNew2!=null&&headNew2 != 0){
            return ResponseInfo.error("该型体颜色已关联大货BOM资料,不能整单删除!");
        }

        //删除型体建档
        rAndDUsageMapper.delTypeFiling(styleNo, styleColor);
        //删除型体注意事项
        rAndDUsageMapper.delPrecautionsForFiling(styleNo, styleColor);
        //型体颜色资料输入
        rAndDUsageMapper.delStyleUsageDetail(styleNo, styleColor);
        //删除全码资料
        rAndDUsageMapper.delFullCodeDetailList(styleNo, styleColor);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 更新全码资料
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getFullCodeDetailRenew(FullCodeRenewRequest request) {
        if (ObjectUtils.isEmpty(request)) {
            log.error("更新全码用量资料参数为空!");
            return ResponseInfo.error("请求参数为空!");
        }

        if (ObjectUtils.isEmpty(request.getList())) {
            return ResponseInfo.error("无全码记录!");
        }

        Set<String> set = new HashSet<>();
        for (FullCodeRequest t : request.getList()) {
            if (!set.add(t.getSizeFrom())){
                return ResponseInfo.error("存在重复号码!");
            }
        }

        String companyId = UserIdThread.get().getCompanyId();
        List<YfBomUsageNew2> list = request.getList().stream().map(s -> {
            YfBomUsageNew2 yfBomUsageNew2 = new YfBomUsageNew2();
            yfBomUsageNew2.setCompanyId(companyId);
            yfBomUsageNew2.setStyleNo(request.getStyleNo());
            yfBomUsageNew2.setStyleColor(request.getStyleColor());
            BeanUtil.copyProperties(s, yfBomUsageNew2);
            return yfBomUsageNew2;
        }).collect(Collectors.toList());

        //删除
        rAndDUsageMapper.delFullCodeDetail(request.getStyleNo(), request.getStyleColor(), request.getList());

        //添加
        rAndDUsageMapper.addFullCodeDetail(list);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 删除全码用量
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getFullCodeDetailDel(FullCodeRenewRequest request) {
        if (ObjectUtils.isEmpty(request)) {
            log.error("删除全码用量资料参数为空!");
            return ResponseInfo.error("请求参数为空!");
        }

        if (ObjectUtils.isEmpty(request.getList())) {
            log.error("删除全码用量资料参数为空!");
            return ResponseInfo.error("请选择全码用量资料!");
        }

        //删除全码用量资料
        rAndDUsageMapper.delFullCodeDetail(request.getStyleNo(), request.getStyleColor(), request.getList());
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 用量明细查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getUsageDetailsQuery(UsageDetailsQueryRequest request) {
        PageRecord<YfBomPartNew2Dto> pageRecord = new PageRecord<>();
        List<YfBomPartNew2Dto> usageDetailsQuery = rAndDUsageMapper.getUsageDetailsQuery(request);
        for (YfBomPartNew2Dto dto : usageDetailsQuery) {
            if (!ObjectUtils.isEmpty(dto.getUsageType())){
                switch (dto.getUsageType()) {
                    case "B":
                        dto.setUsageType(DefineEnum.BASIC_CODE.getValue());
                        break;
                    case "M":
                        dto.setUsageType(DefineEnum.MIDDLE_CODE.getValue());
                        break;
                    case "F":
                        dto.setUsageType(DefineEnum.FULL_CODE.getValue());
                        break;
                    default:
                        dto.setUsageType(null);
                }
            }
        }

        PageInfo list = new PageInfo(usageDetailsQuery);
        pageRecord.setList(usageDetailsQuery);
        pageRecord.setTotal(list.getTotal());

        return ResponseInfo.ok(pageRecord);
    }

    /**
     * 全码用量资料列表
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getFullCodeDetailList(FullCodeRenewGetRequest request) {
        if (ObjectUtils.isEmpty(request)){
            return ResponseInfo.error("参数不能为空!");
        }

        //查询用量资料
        List<YfBomUsageNew2> fullCodeDetailRenewList = rAndDUsageMapper.getFullCodeDetailRenewList(request);
        List<Map<String,String>> list=new ArrayList<>();
        for (YfBomUsageNew2 yfBomUsageNew2 : fullCodeDetailRenewList) {
            Map<String,String> map=new HashMap<>();
            map.put("sizeFrom",yfBomUsageNew2.getSizeFrom());
            map.put("mtlUsage", String.valueOf(yfBomUsageNew2.getMtlUsage()));
            list.add(map);
        }

        return ResponseInfo.ok(list);
    }

    /**
     * 用量变更查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getUsageDetailsChangeQuery(UsageDetailsQueryChangeRequest request) {

        PageRecord<YfBomChangeDto> list = new PageRecord<>();

        //查询用量变更记录
        List<YfBomChangeDto> query = rAndDUsageMapper.getUsageDetailsChangeQuery(request);

        PageInfo list2 = new PageInfo(query);
        list.setList(query);
        list.setTotal(list2.getTotal());
        return ResponseInfo.ok(list);
    }

    /**
     * 型体查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getStyleQuery(UsageDetailsQueryChangeRequest request) {

        PageRecord<String> list = new PageRecord<>();
        //型体查询
        List<String> styleQuery = rAndDUsageMapper.getStyleQuery(request);
        PageInfo list2 = new PageInfo(styleQuery);
        list.setList(styleQuery);
        list.setTotal(list2.getTotal());
        if (ObjectUtils.isEmpty(styleQuery)){
            return ResponseInfo.error("无该型体颜色的BOM资料!");
        }
        return ResponseInfo.ok(list);
    }

    /**
     * 型体颜色图片查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getStyleToColorQuery(UsageDetailsQueryChangeRequest request) {

        PageRecord<StyleToPhotoDto> list = new PageRecord<>();

        //型体颜色图片查询
        List<StyleToPhotoDto> styleToColorQuery = rAndDUsageMapper.getStyleToColorQuery(request);
        PageInfo pageInfo=new PageInfo(styleToColorQuery);
        list.setList(styleToColorQuery);
        list.setTotal(pageInfo.getTotal());

        return ResponseInfo.ok(list);
    }

    /**
     * 型体颜色资料输入查询
     * @param map
     * @return
     */
    @Override
    public ResponseInfo getStyleToColorDetailsQuery(Map<String, String> map) {
        if (ObjectUtils.isEmpty(map)){
            return ResponseInfo.error("参数不能为空!");
        }

        String styleNo = map.get("styleNo");
        String styleColor = map.get("styleColor");

        if (ObjectUtils.isEmpty(styleNo)||ObjectUtils.isEmpty(styleColor)){
            log.error("型体:{},型体颜色:{},两个必须有值!",styleNo,styleColor);
            return ResponseInfo.error("型体或型体颜色为空!");
        }

        List<YfBomPartNew2> styleColorMaterialList = rAndDUsageMapper.getStyleColorMaterialList(styleNo, styleColor);
        List<YfBomPartNewDto> list = styleColorMaterialList.stream().map(s -> {
            YfBomPartNewDto yfBomPartNewDto = new YfBomPartNewDto();
            BeanUtil.copyProperties(s, yfBomPartNewDto);
            if (!ObjectUtils.isEmpty(yfBomPartNewDto.getUsageType())){
                switch (yfBomPartNewDto.getUsageType()) {
                    case "B":
                        yfBomPartNewDto.setUsageType(DefineEnum.BASIC_CODE.getValue());
                        break;
                    case "M":
                        yfBomPartNewDto.setUsageType(DefineEnum.MIDDLE_CODE.getValue());
                        break;
                    case "F":
                        yfBomPartNewDto.setUsageType(DefineEnum.FULL_CODE.getValue());
                        break;
                    default:
                        yfBomPartNewDto.setUsageType(null);
                }
            }
            //调用 DTO 自身方法计算 colorFlag
            yfBomPartNewDto.calculateColorFlag();
            return yfBomPartNewDto;
        }).collect(Collectors.toList());

        return ResponseInfo.ok(list);
    }

    /**
     * 贴合子材料明细
     * @param map
     * @return
     */
    @Override
    public ResponseInfo getDetailsOfAdhesiveSubMaterials(Map<String, String> map) {
        String mtlNo = map.get("mtlNo");
        //贴合子材料明细
        List<YfSubMtlTemp2Dto> materials = rAndDUsageMapper.getDetailsOfAdhesiveSubMaterials(mtlNo);
        return ResponseInfo.ok(materials);
    }

    /**
     * 修改
     * @param map
     * @param choose
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getDetailsOfAdhesiveSubMaterialsUpdate(Map<String, String> map, Integer choose) {
        if (ObjectUtils.isEmpty(map)) {
            return ResponseInfo.error("参数不能为空!");
        }
        String mtlNo = map.get("mtlNo");
        String mtlSeq = map.get("mtlSeq");
        String percent = map.get("percent");
        if (ObjectUtils.isEmpty(mtlNo) || ObjectUtils.isEmpty(mtlSeq)) {
            return ResponseInfo.error("物料编码或序号为空!");
        }
        //定义标记
        String flag = null;
        //0请购,1不请购
        switch (choose) {
            case 0:
                flag = DefineEnum.CHECKOUT_FLAG.getValue();
                //修改
                rAndDUsageMapper.UpdateDetailsOfAdhesiveSubMaterials(mtlNo, mtlSeq, flag,percent);
                YfBomFitSub material = getDetailsOfAdhesiveSubMaterial(mtlNo, mtlSeq);

                YfBomFitSubLog subLog = new YfBomFitSubLog();
                BeanUtil.copyProperties(material, subLog);
                subLog.setPercent(BigDecimal.valueOf(Double.parseDouble(percent)));
                subLog.setSysDate(LocalDateTime.now());
                subLog.setRemark(DefineEnum.PURCHASE_REQUEST.getValue());
                subLog.setSysUser(UserIdThread.get().getUserName());

                //插入
                rAndDUsageMapper.addDetailsOfAdhesiveSubMaterials(subLog);
                break;
            default:
                //修改
                rAndDUsageMapper.UpdateDetailsOfAdhesiveSubMaterials(mtlNo, mtlSeq, flag,percent);
                YfBomFitSub subMaterial = getDetailsOfAdhesiveSubMaterial(mtlNo, mtlSeq);

                YfBomFitSubLog Log = new YfBomFitSubLog();
                BeanUtil.copyProperties(subMaterial, Log);
                Log.setPercent(BigDecimal.valueOf(Double.parseDouble(percent)));
                Log.setSysDate(LocalDateTime.now());
                Log.setRemark(DefineEnum.NO_PURCHASE_REQUEST.getValue());
                Log.setSysUser(UserIdThread.get().getUserName());

                //插入
                rAndDUsageMapper.addDetailsOfAdhesiveSubMaterials(Log);
                break;
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 查询型体颜色材料
     * @param mtlNo
     * @param mtlSeq
     */
    private YfBomFitSub getDetailsOfAdhesiveSubMaterial(String mtlNo,String mtlSeq){
        YfBomFitSub details = rAndDUsageMapper.getDetailsOfAdhesiveSubMaterial(mtlNo, mtlSeq);
        return details;
    }

    /**
     * 复制用量列表
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getCopyingDosageList(CopyingDosageQueryRequest request) {
        if (request == null || ObjectUtils.isEmpty(request.getCurrentStyleNo()) || ObjectUtils.isEmpty(request.getCurrentStyleColor())) {
            return ResponseInfo.error("请求参数为空!");
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(),request.getPageSize());
        List<CopyingDosageListDto> copyingDosageList = rAndDUsageMapper.getCopyingDosageList(request);

        PageRecord<CopyingDosageListDto> list = new PageRecord<>();
        PageInfo pageInfo = new PageInfo(copyingDosageList);
        list.setList(copyingDosageList);
        list.setTotal(pageInfo.getTotal());

        return ResponseInfo.ok(list);
    }

    /**
     * 复制用量
     * @param request
     * @return
     */
    @Override
    public ResponseInfo getCopyingDosage(CopyingDosageRequest request) {
        if (ObjectUtils.isEmpty(request)) {
            return ResponseInfo.error("请求参数为空!");
        }

        if (ObjectUtils.isEmpty(request.getList())) {
            return ResponseInfo.error("请选择记录");
        }

        //记录检验条数
        int count = 0;
        for (StyleNoToColorRequest s : request.getList()) {
            if (!ObjectUtils.isEmpty(s)&&!ObjectUtils.isEmpty(s.getCfmFlag())) {
                if (s.getCfmFlag().equals(DefineEnum.CHECKOUT_FLAG.getValue())){
                    count++;
                }
            }
        }
        if (count > 0) {
            return ResponseInfo.error(count + "条记录已检核,不能处理!");
        }

        //定义冲刀号计数
        int cutCount = 0;
        //获取当前型体的冲刀号
        List<String> currentSize = rAndDUsageMapper.getTypeSize(request.getCurrentStyleNo());
        if (!ObjectUtils.isEmpty(currentSize)) {
            for (StyleNoToColorRequest s : request.getList()) {
                //查询被复制的冲刀号
                List<String> copySize = rAndDUsageMapper.getTypeSize(s.getStyleNo());

                if (!ObjectUtils.isEmpty(copySize)) {
                    //判断元素是否存在
                    boolean exists = currentSize.stream().anyMatch(size -> copySize.contains(size));
                    if (!exists) {
                        cutCount++;
                    }
                }
            }
        }
        if (cutCount > 0) {
            return ResponseInfo.error(cutCount + "条记录冲刀号不一样,不能处理!");
        }

        //查询当前型体颜色资料
        List<YfBomPartNew2> currentList = rAndDUsageMapper.getStyleColorMaterialList(request.getCurrentStyleNo(), request.getCurrentStyleColor());
        if (!ObjectUtils.isEmpty(currentList)) {
            for (StyleNoToColorRequest s : request.getList()) {

                //被复制的型体颜色资料
                List<YfBomPartNew2> copyList = rAndDUsageMapper.getStyleColorMaterialList(s.getStyleNo(), s.getStyleColor());
                if (!ObjectUtils.isEmpty(copyList)) {
                    currentList.stream().forEach(current -> {
                        //判断被复制集合是否存在满足条件的元素
                        boolean found = copyList.stream().anyMatch(copy -> current.getPartName().equals(copy.getPartName()));

                        if (found) {
                            //进行复制操作
                            YfBomPartNew2 yfBomPartNew2 = copyList.stream()
                                    .filter(c -> current.getPartName().equals(c.getPartName()) && current.getSegment().equals(c.getSegment()))
                                    .findFirst()
                                    .orElse(null);

                            if (yfBomPartNew2 != null) {
                                yfBomPartNew2.setUsage(current.getUsage());
                            }

                            //修改用量
                            rAndDUsageMapper.updateCopyingDosage(yfBomPartNew2.getStyleNo(),
                                    yfBomPartNew2.getStyleColor(),
                                    yfBomPartNew2.getPartName(),
                                    yfBomPartNew2.getSegment(),
                                    yfBomPartNew2.getUsage());
                        }
                    });
                }
            }
        }

        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 重排序号
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo getReordering(StyleNoToColorRequest request) {
        if (ObjectUtils.isEmpty(request.getStyleNo()) || ObjectUtils.isEmpty(request.getStyleColor())) {
            log.error("型体:{},颜色:{},必要参数为空!", request.getStyleNo(), request.getStyleColor());
            return ResponseInfo.error("必要参数为空!");
        }

        if (!ObjectUtils.isEmpty(request.getCfmFlag())){
            if (request.getCfmFlag().equals(DefineEnum.CHECKOUT_FLAG.getValue())) {
                return ResponseInfo.error("已检验，不能处理!");
            }
        }

        //查询型体颜色BOM
        List<YfBomPartNew2> list = rAndDUsageMapper.getStyleColorMaterialList(request.getStyleNo(), request.getStyleColor());
        if (!ObjectUtils.isEmpty(list)) {

            //生成一个整数流
            List<YfBomPartNew2> updatedList = IntStream.range(0, list.size())
                    //映射对象
                    .mapToObj(i -> {
                        YfBomPartNew2 yfBomPartNew2 = new YfBomPartNew2();
                        BeanUtil.copyProperties(list.get(i), yfBomPartNew2);
                        yfBomPartNew2.setSeqNo(String.valueOf(i + 1));
                        return yfBomPartNew2;
                    })
                    .collect(Collectors.toList());
            //删除
            rAndDUsageMapper.delStyleUsageDetail(request.getStyleNo(), request.getStyleColor());

            //添加
            rAndDUsageMapper.addStyleUsageDetail(updatedList);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 颜色代码更新
     * @param styleNo
     * @return
     */
    @Override
    public ResponseInfo ColorCodeUpdate(String styleNo) {
        List<YfStyleColorDetail> colorList = largeCargoTypeMapper.getStyleColorDetail(styleNo);

        UsageDetailsQueryChangeRequest re = new UsageDetailsQueryChangeRequest();
        re.setStyleNo(styleNo);
        List<StyleToPhotoDto> list = rAndDUsageMapper.getStyleToColorQuery(re);

        if (!ObjectUtils.isEmpty(colorList)&& !ObjectUtils.isEmpty(list)){
            for (YfStyleColorDetail dto : colorList) {
                for (StyleToPhotoDto t : list) {
                    if (dto.getStyleNo().equals(t.getStyleNo())&& dto.getStyleColor().equals(t.getStyleColor())){
                        if (!ObjectUtils.isEmpty(dto.getColorCode())){
                            t.setColorCode(dto.getColorCode());
                        }else {
                            t.setColorCode(null);
                        }
                        rAndDUsageMapper.updateBomColorCode(t.getStyleNo(),t.getStyleColor(),dto.getColorCode());
                    }
                }
            }
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 修改基本码
     * @param request
     * @return
     */
    @Override
    public ResponseInfo updateBaseSize(StyleColorMaterialAddRequest request) {
        if (StringUtils.isEmpty(request.getStyleNo()) || StringUtils.isEmpty(request.getStyleColor())) {
            return ResponseInfo.error("型体或型体颜色不能为空!");
        }
        //判断是否检验
        String flag = rAndDUsageMapper.checkout(request.getStyleNo(), request.getStyleColor());
        if (!ObjectUtils.isEmpty(flag) && flag.equals(DefineEnum.CHECKOUT_FLAG.getValue())) {
            return ResponseInfo.error("型体:" + request.getStyleNo() + "/颜色:" + request.getStyleColor() + ",BOM资料已检验,不能修改!");
        }
        //型体基本号
        rAndDUsageMapper.updateBaseSize(request.getBaseSize(),request.getStyleNo(),request.getStyleColor());
        return ResponseInfo.ok("操作成功!");
    }
}
